package top.techqi.hamtools.ext

import android.support.annotation.ColorInt
import android.text.SpannableStringBuilder
import android.text.Spanned
import android.text.style.ForegroundColorSpan

fun CharSequence?.highlight(needle: String, @ColorInt color: Int, ignoreCase: Boolean = false): SpannableStringBuilder {
    val ssb = SpannableStringBuilder(this ?: "")
    if (needle.isNotBlank()) {
        val length = needle.length
        var start = ssb.indexOf(needle, ignoreCase = ignoreCase)
        while (start >= 0) {
            val end = start + length
            ssb.setSpan(ForegroundColorSpan(color), start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
            start = ssb.indexOf(needle, end, ignoreCase)
        }
    }
    return ssb
}